package core

import (
	"fmt"
	"gitee.com/feimos/dm/utils"
	"log"
	"os"
	"path/filepath"
)

func AddOneDocument(yamlContent *YamlContent, file string, ignoreList []string, writeYaml bool) error {

	root := yamlContent.Root
	path := utils.JoinPath(root, file)

	if utils.MatchIgnore(path, ignoreList, true) {
		return nil
	}

	stat, err := os.Stat(path)

	if err != nil {
		return err
	}

	if stat.IsDir() {
		return fmt.Errorf("document path \"%v\" is found to be a folder, only file path is accepted\n", path)
	}

	fileInfo := CreateFileInfo(path, stat)

	ext := fileInfo.Ext
	name := fileInfo.Name
	dir := utils.JoinPath(root, ext)

	yamlContent.AddItem(ext, fileInfo)

	isCreated, err := utils.CreateDir(dir)

	if isCreated {
		log.Printf("create folder \"%v\"\n", dir)
	}

	if err != nil {
		return err
	}

	newPath := utils.JoinPath(root, ext, name)

	err = os.Rename(path, newPath)
	if err != nil {
		return err
	}

	log.Printf("add document \"%v\" successfully\n", name)

	if writeYaml {
		err := WriteYaml(yamlContent, true)
		if err != nil {
			return err
		}

	}

	return nil
}

func AddGlob(yamlContent *YamlContent, pattern string, ignoreList []string) error {

	matches, err := filepath.Glob(pattern)

	if err != nil {
		return err
	}

	for _, file := range matches {

		info, err := os.Stat(file)

		if err != nil {
			return err
		}

		if info.IsDir() || file == DmFile || file == DmIgnoreFile {
			continue
		}

		err = AddOneDocument(yamlContent, file, ignoreList, false)
		if err != nil {
			return err
		}
	}

	err = WriteYaml(yamlContent, true)
	if err != nil {
		return err
	}

	return nil
}
